package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.config.minio.MinioAutoConfiguration;
import com.atguigu.gmall.product.config.minio.MinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) throws Exception {
        //1.创建出minio的客户端

        //2.检查存储桶是否已经存在
        boolean isExist = minioClient.bucketExists(minioProperties.getBucketName());
        if (isExist){
            System.out.println("Bucket already exists.");
        } else {
            //3.创建一个名为gmall的存储桶
            minioClient.makeBucket("gmall");
        }
        //4.使用putObject上传一个文件到存储桶中
        String filename = UUID.randomUUID().toString().replace("-","") + "/" +file.getOriginalFilename();
        String date = DateUtil.formatDate(new Date());
        InputStream inputStream = file.getInputStream();

        //文件上传参数:Long objectSize ,long partSize
        PutObjectOptions options = new PutObjectOptions(file.getSize(),-1L);
        String contentType = file.getContentType();
        options.setContentType(contentType);
        minioClient.putObject("gmall",
                date + "/" +filename,
                inputStream,
                options);
        //返回刚上传文件的可访问路径
        String url =  minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + date + "/" + filename;
        return url;
    }
}
